﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ApiResult<int>>
    {
        IBaseReponsitory<Roles> Roles;

        public UpdateRoleCommandHandler(IBaseReponsitory<Roles> Roles)
        {
            this.Roles = Roles;
        }

        public async Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            var Tst = Roles.GetQuery().Where(x => x.Role_Name == request.Roles.Role_Name && x.Role_Id != request.Roles.Role_Id&&!x.Role_IsDeleted).ToList();
            if (Tst.Count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "角色名称已存在",
                    Data = -1
                };
            }
            else
            {
                var list = await Roles.GetQuery().FirstOrDefaultAsync(c => c.Role_Id == request.Roles.Role_Id);
                list.Role_Name = request.Roles.Role_Name;
                list.Role_Creater = request.Roles.Role_Creater;
                list.CreateTime = request.Roles.CreateTime;
                list.Role_Updater = request.Roles.Role_Updater;
                list.Role_UpdeTime =DateTime.Now;
                list.Role_IsDeleted = request.Roles.Role_IsDeleted;
                await Roles.UpdateAsync(list);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "修改成功",
                    Data = 1

                };
            }
        }
    }
}
